<!--
 * @Description: 
 * @Version: 2.0
 * @Autor: snzo.chen
 * @Date: 2023-11-21 09:50:52
 * @LastEditors: snzo.chen
 * @LastEditTime: 2023-12-01 16:56:47
-->
<template>
  <div class="auth-box">
    <a-checkbox
      v-model:checked="state.checkAll"
      :indeterminate="state.indeterminate"
      @change="onCheckAllChange"
    >
      全选
    </a-checkbox>
    <a-divider />
    <a-checkbox-group v-model:value="state.checkedList" :options="options">
      <template #label="{ label }">
        <span>{{ label }}</span>
      </template>
    </a-checkbox-group>
  </div>
</template>
<script lang="ts" setup>
interface optionsItem {
  label: string | undefined;
  value: string | number | undefined;
}

interface State {
  indeterminate: boolean;
  checkAll: boolean;
  checkedList: Array<number | undefined>;
}
import { ref, watch, reactive, onMounted } from "vue";
import { selectAllAuth } from "@/api/system/auth";
const props = defineProps({
  roleId: {
    type: Number,
    default: 0,
  },
  roleAuthOfData: {
    type: Array,
    default: [],
  },
});
const options = ref<optionsItem[]>([]);

const state = reactive<State>({
  indeterminate: false,
  checkAll: false,
  checkedList: [],
});

const onCheckAllChange = (e: any) => {
  Object.assign(state, {
    checkedList: e.target.checked
      ? options.value.map((item) => {
          return item.value;
        })
      : [],
    indeterminate: false,
  });
};

let allRoleAuthData: API.AuthItem[] = [];

watch(
  () => state.checkedList,
  (val) => {
    state.indeterminate = !!val.length && val.length < options.value.length;
    state.checkAll = val.length === options.value.length;
  }
);

const loadAuthData = async () => {
  allRoleAuthData = await selectAllAuth();
  options.value = allRoleAuthData.map((item) => {
    return {
      label: item.authName,
      value: item.id,
    };
  });
  filterRoleData();
};

const filterRoleData = () => {
  const roleData = props.roleAuthOfData;
  state.checkedList =
    roleData.length > 0
      ? roleData.map((item: API.AuthItem) => {
          return item.id;
        })
      : [];
};

onMounted(() => {
  loadAuthData();
});

const getRoleAuth = () => {
  const roleAuth = state.checkedList.map((item) => {
    return { roleId: props.roleId, authId: item };
  });
  return roleAuth;
};

defineExpose({
  getRoleAuth,
});
</script>
<style lang="less" scoped>
.auth-box {
  padding: 30px;

  :deep(.ant-checkbox-group-item) {
    margin-bottom: 10px;
  }
}
</style>
